package com.shitou.shitoucart.service.impl;

import com.alibaba.fastjson.JSON;
import com.shitou.shitoucart.entity.MemberCartEntity;
import com.shitou.shitoucart.feign.ProductFeign;
import com.shitou.shitoucart.service.MemberCartService;
import com.shitou.shitoucart.vo.CartVo;
import com.shitou.shitoucart.vo.RespCartVo;
import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.AllSaltEnum;
import com.shitou.shitoucommons.utils.RespBean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;
import org.springframework.data.redis.core.StringRedisTemplate;


import com.shitou.shitoucart.dao.CartDao;
import com.shitou.shitoucart.entity.CartEntity;
import com.shitou.shitoucart.service.CartService;
import org.apache.shiro.crypto.hash.Sha256Hash;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("all")
@Service("cartService")
public class CartServiceImpl extends ServiceImpl<CartDao, CartEntity> implements CartService {

    @Autowired
    private MemberCartService memberCartService;

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Getter
    @AllArgsConstructor
    enum GetCart{
        GETMEMBER_CART(1),
        GETMEMBER_SEARCH_CART(2)

        ;
        private int code;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CartEntity> page = this.page(
                new Query<CartEntity>().getPage(params),
                new QueryWrapper<CartEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 添加购物车
     * @param cartVo
     * @see CartVo
     * @return
     */
    @Override
    public RespBean addCart(CartVo cartVo, HttpServletRequest request, HttpServletResponse response) {

        // 检查是否是自己发布的商品，不能将自己的商品加入购物车
        checkPublisherIsMyself(cartVo.getMemberId(), cartVo.getCart().getSpuId());

        // 在加入购物车的一瞬间，判断该商品被售卖，如果被售卖则返回error
        String productToken = String.valueOf(new Sha256Hash(cartVo.getCart().getSpuId().toString(), AllSaltEnum.SALT.getSalt()));

        String test = redisTemplate.opsForValue().get("saleCount:" + productToken);
        Integer saleCount = Integer.valueOf(test);
        if ( saleCount != 0 ){
            return RespBean.success("该商品已经被售卖");
        }
        Date date = new Date();
        // 兄弟们，啥也不干就是加！！！
        CartEntity cart = cartVo.getCart();
        // 查询购物车信息，并且如果已经有了，但是关联的是其他用户的，那么再次加入购物车，并关联用户
        List<CartEntity> cartDos = this.list(new QueryWrapper<CartEntity>()
                .eq("spu_id", cart.getSpuId()));

        if ( cartDos.size() > 0 ){
            // 不为空，判断是否关联的是当前用户,，如果是，则更新，否则添加
            for (CartEntity cartDo : cartDos) {
                MemberCartEntity memberCart = memberCartService.getOne(
                        new QueryWrapper<MemberCartEntity>().eq("cart_id", cartDo.getId()));
                // 当前用户已经进行了添加,更新
                if (memberCart.getMemberId() == cartVo.getMemberId()) {
                    cart.setId(memberCart.getId());
                    cart.setUpdateTime(date);
                    cart.setStatus(1);
                    this.updateById(cart);
                    return RespBean.success();
                }
            }
        }

        cart.setCreateTime(date);
        cart.setUpdateTime(date);
        baseMapper.insert(cart);

        MemberCartEntity memberCartEntity = new MemberCartEntity();
        memberCartEntity.setCartId(cart.getId());
        memberCartEntity.setMemberId(cartVo.getMemberId());
        memberCartService.save(memberCartEntity);

        return RespBean.success();
    }

    /**
     * 获得用户购物车
     * @param memberId
     * @return
     */
    @Override
    public RespBean getMemberCart(long memberId, HttpServletRequest request, HttpServletResponse response) {
        return getAllProduct(memberId,null, GetCart.GETMEMBER_CART.getCode(), request, response);
    }

    /**
     * 删除购物车
     * @param cartId
     * @return
     */
    @Override
    public RespBean removeMemberCart(long cartId, long memberId ) {

        // 差购物车
        CartEntity id = this.getOne(new QueryWrapper<CartEntity>().eq("id", cartId)
                .eq("status", 1));
        if ( id != null ){
            // 通过购物车反向获取用户， 并判断两者的id是否相等
            MemberCartEntity memberCart = memberCartService.getOne(new QueryWrapper<MemberCartEntity>()
                    .eq("cart_id", id.getId()));
            if ( memberCart != null && memberCart.getMemberId().equals(memberId)){
                id.setUpdateTime(new Date());
                id.setStatus(0);
            }else {
                throw new RRException("用户越权操作");
            }
        }else {
            throw new RRException("购物车信息错误");
        }
        this.updateById(id);
        return RespBean.success();
    }



    /**
     * 搜索购物车
     * @param searchInfo
     * @return
     */
    @Override
    public RespBean searchCart(String searchInfo, long memberId, HttpServletRequest request, HttpServletResponse response) {
        return getAllProduct(memberId, searchInfo,GetCart.GETMEMBER_SEARCH_CART.getCode(), request, response);
    }


    /**
     * 获取用户当前购物车里面的所有商品信息
     * @param memberId 用户id
     * @param searchInfo 搜索的内容，如果是获得当前购物车的话，传入null
     * @param tag 判断查询的是什么
     *            [ 1-获用户当前购物车，2-用户搜索购物车 ]
     * @return
     */
    public RespBean getAllProduct(long memberId, String searchInfo, int tag, HttpServletRequest request, HttpServletResponse response){

        if ( memberId == 0 ){
            return RespBean.error();
        }
        if ( (searchInfo == null || searchInfo.equals("")) && tag == GetCart.GETMEMBER_SEARCH_CART.getCode()){
            return RespBean.success().put("data", null);
        }
        List<MemberCartEntity> memberCartEntityList = memberCartService.list(
                new QueryWrapper<MemberCartEntity>().eq("member_id", memberId));
        List<RespCartVo> list = new ArrayList<>();

        long[] spuIds = new long[memberCartEntityList.size() == 1?2:memberCartEntityList.size()];
        int index = -1;

        // 筛选状态为1的购物车
        for (MemberCartEntity memberCartEntity : memberCartEntityList) {
            RespCartVo respCartVo = new RespCartVo();

            CartEntity cart = null;
            if ( tag == GetCart.GETMEMBER_CART.getCode() ){
                cart = this.getOne(new QueryWrapper<CartEntity>().eq("id", memberCartEntity.getCartId()));
            } else if ( tag == GetCart.GETMEMBER_SEARCH_CART.getCode()){
                cart = this.getOne( new QueryWrapper<CartEntity>().eq("id", memberCartEntity.getCartId())
                        .and(new Consumer<QueryWrapper<CartEntity>>() {
                            @Override
                            public void accept(QueryWrapper<CartEntity> cartEntityQueryWrapper) {
                                cartEntityQueryWrapper.like("spu_title", searchInfo).or().like("spu_detail", searchInfo);
                            }
                        }));
            }
            // 剔除状态为0 的购物车
            if ( cart == null || cart.getStatus() != 1) {
                continue;
            }
            respCartVo.setCart(cart);
            spuIds[++index] = cart.getSpuId();
            list.add(respCartVo);
        }
        // 远程调用接口进行商品 是否可以售卖 判断
        return feignSale(spuIds, index, list, request, response);
    }


    /**
     * 远程调用，判断该商品是否已经售卖
     * @param spuIds
     * @param index
     * @param list
     * @return
     */
    public RespBean feignSale(long[] spuIds, int index, List<RespCartVo> list, HttpServletRequest request, HttpServletResponse response){
        boolean tag = false;
        if ( spuIds.length == 1 ){
            spuIds[++index] = 0;
            tag = true;
        }
        RespBean respBean = productFeign.checkSaleCount(spuIds);
        long[] data = JSON.parseObject((String) respBean.get("data"), long[].class);

        for ( int i = 0 ; i <  (tag?1:list.size()); i ++){
            list.get(i).setSale(data[i]);
        }
        return RespBean.success().put("data", list.size()==0?null:list);
    }



    /**
     * 检查该商品是否是自己的商品
     * @param memberId
     * @param spuId
     * @return
     */
    public void checkPublisherIsMyself(Long memberId, Long spuId){
        String data = null;
        try {
            RespBean respBean = productFeign.checkPublisherIsMyself(memberId, spuId);
            if ( respBean == null ){
                throw new RRException("收藏商品失败，请联系管理员");
            }
            data = (String) respBean.get("data");
        } catch (Exception e){
            throw new RRException("收藏商品失败，请联系管理员");
        }
        System.out.println(data);
        boolean isMyselfProduct = Boolean.parseBoolean(data);
        System.out.println(isMyselfProduct);
        if ( isMyselfProduct ){
            throw new RRException("不能收藏自己的商品哦");
        }
    }
}
